<template>
  <div class="container">
    <van-list
      v-model="loading"
      :finished="finished"
      @load="onLoad"
      class="news-list"
    >
      <van-checkbox-group
        class="card-goods"
        v-model="checkedGoods"
      >
        <div
          v-for="(item, key) in list"
          v-bind:key="key"
          :name="item.id"
          class="card-goods-box"
        >
          <van-checkbox
            class="card-goods__item"
            :key="item.id"
            :name="item.id"
            :disabled="!editmode && !item.status"
          >选中</van-checkbox>
          <van-card
            :title="item.name"
            :thumb="item.thumb"
            v-if="editmode"
          >
            <van-cell
              slot="desc"
              :title="item.sku"
              is-link
              @click="onCheckSku(item.id)"
            />
            <div
              slot="footer"
              class="flexbox"
            >
              <div class="price-cny">{{formatPrice(item.price)}}</div>
            </div>
          </van-card>
          <van-card
            :title="item.name"
            :desc="formatDescription(item.sku,item.stock)"
            :thumb="item.thumb"
            @click.native="onClickView(item.id)"
            v-else
          >
            <div
              slot="footer"
              class="flexbox"
              @click.stop
            >
              <div class="price-cny">{{formatPrice(item.price)}}</div>
              <van-stepper
                v-model="item.num"
                v-if="item.status"
                integer
                :min="1"
                :max="item.stock"
                :disabled="!item.status"
                :step="1"
                @change="changeNumber(item.id, $event)"
              />
              <van-button
                size="small"
                id="van-button"
                @click="onRemove(item.id, key)"
                v-else
              >删除</van-button>
            </div>
          </van-card>
        </div>
      </van-checkbox-group>
    </van-list>
    <van-sku
      v-model="showBase"
      :sku="sku.sku"
      :goods="sku.goods_info"
      :goods-id="sku.goods_id"
      :hide-stock="sku.sku.hide_stock"
      :quota="sku.quota"
      :quota-used="sku.quota_used"
      :show-add-cart-btn="false"
      reset-stepper-on-hide
      reset-selected-sku-on-hide
      disable-stepper-input
      :close-on-click-overlay="closeOnClickOverlay"
      @buy-clicked="onBuyClicked"
    />
    <van-goods-action v-if="editmode">
      <van-checkbox
        v-model="checkedAll"
        @change="changeState"
        :disabled="!list.length"
      >全选</van-checkbox>
      <van-goods-action-button
        text="移入收藏"
        @click="onClickMoveToCollect"
      />
      <van-goods-action-button
        text="删除"
        @click="onDelete"
        primary
      />
    </van-goods-action>
    <van-submit-bar
      :price="totalPrice"
      :disabled="!checkedGoods.length"
      :button-text="submitBarText"
      @submit="onSubmit"
      v-else
    >
      <van-checkbox
        v-model="checkedAll"
        @change="changeState"
        :disabled="!list.length"
      >全选</van-checkbox>
    </van-submit-bar>
    <div class="placeholder"></div>
  </div>
</template>

<script>
import {
  Tag,
  Col,
  Icon,
  Cell,
  CellGroup,
  Popup,
  Sku,
  Button,
  Panel,
  PullRefresh,
  Lazyload,
  List,
  Checkbox,
  CheckboxGroup,
  Card,
  Stepper,
  SubmitBar,
  GoodsAction,
  GoodsActionButton,
  GoodsActionIcon,
  Toast
} from 'vant'

export default {
  components: {
    [Tag.name]: Tag,
    [Col.name]: Col,
    [Icon.name]: Icon,
    [Cell.name]: Cell,
    [CellGroup.name]: CellGroup,
    [Panel.name]: Panel,
    [Popup.name]: Popup,
    [Sku.name]: Sku,
    [Button.name]: Button,
    [PullRefresh.name]: PullRefresh,
    [Lazyload.name]: Lazyload,
    [List.name]: List,
    [Card.name]: Card,
    [Stepper.name]: Stepper,
    [Checkbox.name]: Checkbox,
    [SubmitBar.name]: SubmitBar,
    [GoodsAction.name]: GoodsAction,
    [GoodsActionButton.name]: GoodsActionButton,
    [GoodsActionIcon.name]: GoodsActionIcon,
    [CheckboxGroup.name]: CheckboxGroup
  },

  data () {
    return {
      showBase: false,
      closeOnClickOverlay: true,
      editmode: false,
      list: [],
      loading: false,
      finished: false,
      count: 0,
      show: false,
      meta: {
        totalCount: 0,
        pageCount: 0,
        currentPage: 0,
        perPage: 0
      },
      checkedAll: false,
      checkedGoods: [],
      isIndeterminate: [],
      sku: {
        kdt_id: 55,
        user_id: 4674509,
        offline_id: 0,
        activity_alias: '',
        sku: {
          tree: [
            {
              k: '颜色',
              k_id: '1',
              v: [
                {
                  id: '30349',
                  name: '天蓝色',
                  imgUrl:
                    'https://img.yzcdn.cn/upload_files/2017/02/21/FjKTOxjVgnUuPmHJRdunvYky9OHP.jpg!100x100.jpg'
                }
              ],
              k_s: 's1',
              count: 2
            },
            {
              k: '尺码',
              k_id: '2',
              v: [
                {
                  id: '1193',
                  name: 'S'
                },
                {
                  id: '1194',
                  name: 'M'
                },
                {
                  id: '1195',
                  name: 'L'
                },
                {
                  id: '1196',
                  name: 'XL'
                },
                {
                  id: '1197',
                  name: 'XXL'
                }
              ],
              k_s: 's2',
              count: 2
            }
          ],
          list: [
            {
              id: 2259,
              price: 100,
              discount: 100,
              code: '',
              s1: '1215',
              s2: '1193',
              s3: '0',
              s4: '0',
              s5: '0',
              extend: null,
              kdt_id: 55,
              discount_price: 0,
              stock_num: 110,
              stock_mode: 0,
              is_sell: null,
              combin_sku: false,
              goods_id: 946755
            },
            {
              id: 2260,
              price: 100,
              discount: 100,
              code: '',
              s1: '1215',
              s2: '1194',
              s3: '0',
              s4: '0',
              s5: '0',
              extend: null,
              kdt_id: 55,
              discount_price: 0,
              stock_num: 0,
              stock_mode: 0,
              is_sell: null,
              combin_sku: false,
              goods_id: 946755
            },
            {
              id: 2257,
              price: 100,
              discount: 100,
              code: '',
              s1: '30349',
              s2: '1193',
              s3: '0',
              s4: '0',
              s5: '0',
              extend: null,
              kdt_id: 55,
              discount_price: 0,
              stock_num: 111,
              stock_mode: 0,
              is_sell: null,
              combin_sku: false,
              goods_id: 946755
            },
            {
              id: 2258,
              price: 100,
              discount: 2,
              code: '',
              s1: '30349',
              s2: '1194',
              s3: '0',
              s4: '0',
              s5: '0',
              extend: null,
              kdt_id: 55,
              discount_price: 0,
              stock_num: 6,
              stock_mode: 0,
              is_sell: null,
              combin_sku: false,
              goods_id: 946755
            }
          ],
          price: '100.00',
          stock_num: 227,
          collection_id: 2261,
          collection_price: 0,
          none_sku: false,
          sold_num: 0,
          min_price: '1.00',
          max_price: '1.00',
          hide_stock: false
        },
        goods_id: '946755',
        alias: '2oml0r0n5vytj',
        quota: 0,
        is_virtual: '0',
        quota_used: 0,
        goods_info: {}
      }
    }
  },

  created () {
    this.listenShopCartEdit()
  },

  watch: {
    checkedGoods: {
      handler () {
        if (this.checkedGoods.length === this.list.length) {
          this.checkedAll = true
        } else {
          if (this.checkedGoods.length + 1 === this.list.length) {
            this.isIndeterminate = this.checkedGoods
          }
          this.checkedAll = false
        }
      },
      deep: true
    },
    paymode: {
      handler (curVal, oldVal) {
        console.log('当前编辑状态：', curVal)
        console.log('之前编辑状态：', oldVal)
      },
      deep: true
    }
  },

  computed: {
    submitBarText () {
      const count = this.checkedGoods.length
      return '结算' + (count ? '(' + count + ')' : '')
    },

    totalPrice () {
      return this.list.reduce(
        (total, item) =>
          total +
          (this.checkedGoods.indexOf(item.id) !== -1
            ? item.price * 100 * item.num
            : 0),
        0
      )
    }
  },
  methods: {
    onLoad () {
      this.axios
        .get('/shop/cart', {
          headers: { FastMode: true }
        })
        .then(response => {
          let data = response.data
          let itemCount = data.items.length
          if (itemCount > 0) {
            this.list = this.list.concat(data.items)
            this.list.forEach((value, index) => {
              if (value.checked && value.status) {
                this.checkedGoods.push(value.id)
              }
            })
          }
          this.meta = data.meta
          this.loading = false
          if (this.meta.pageCount <= this.meta.currentPage || itemCount <= 0) {
            this.finished = true
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    onCheckSku (id) {
      this.axios
        .get('/shop/spu/' + id, {
          headers: { FastMode: true }
        })
        .then(response => {
          this.sku = response.data
          this.showBase = true
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    onClickView (id) {
      Toast('商品详情显示' + id)
    },
    onBuyClicked (data) {
      Toast(JSON.stringify(data))
    },
    changeNumber (id, num) {
      console.log(id, num)
      // this.axios
      //   .get('/shop/cart/change', {
      //     params: { id: id, num: num },
      //     headers: { FastMode: true }
      //   })
      //   .then(response => {
      //     this.sku = response.data
      //     this.showBase = true
      //   })
      //   .catch(function (error) {
      //     console.log(error)
      //   })
    },
    onClickMoveToCollect () {
      Toast('移入收藏' + JSON.stringify(this.checkedGoods))
    },
    onDelete () {
      Toast('删除' + JSON.stringify(this.checkedGoods))
    },
    onRemove (id, index) {
      this.axios
        .get('/shop/cart/remove', {
          params: { id: id },
          headers: { FastMode: true }
        })
        .then(response => {
          if (response.data) {
            this.list.splice(index, 1)
          } else {
            Toast('移除失败')
          }
        })
        .catch(function (error) {
          console.log(error)
        })
    },
    arrayUnique (arr) {
      let result = []
      let hash = {}
      for (let i = 0, elem; (elem = arr[i]) != null; i++) {
        if (!hash[elem.id]) {
          result.push(elem)
          hash[elem.id] = true
        }
      }
      return result
    },
    formatPrice (price) {
      return price.toFixed(2)
    },
    formatDescription (sku, stock) {
      if (stock > 0) {
        return sku
      }
      return sku + '（库存不足）'
    },
    onSubmit () {
      let goods = []
      for (let i = 0; i < this.list.length; i++) {
        let item = this.list[i]
        if (this.checkedGoods.indexOf(item.id) !== -1) {
          goods.push({ id: item.id, num: item.num })
        }
      }
      this.axios
        .post(
          '/shop/cart/balance',
          {
            items: goods
          },
          {
            headers: { FastMode: true }
          }
        )
        .then(response => {
          if (response.data) {
            this.pushWeblink(this.domain + 'balance')
          }
        })
        .catch(function (error) {
          console.log(error)
          Toast('重置失败')
        })
    },
    changeState (item) {
      this.checkedGoods = []
      if (item) {
        this.list.forEach((value, index) => {
          if (this.editmode || value.status) {
            this.checkedGoods.push(value.id)
          }
        })
      } else {
        this.checkedGoods = this.isIndeterminate
      }
      this.isIndeterminate = []
    },
    listenShopCartEdit () {
      this.jsBridge.shopCartEdit(res => {
        console.log('购物车编辑回调监听: ', res)
        this.editmode = res.isEdit
        console.log('编辑状态: ', this.editmode)
      })
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style lang="less" scoped>
.tips {
  background: #d8e8f8;
  color: #047bb3;
  font-size: 0.2rem;
  margin: 0;
  padding: 0.2rem 0.3rem;
  text-align: center;
  font-weight: normal;
}

/deep/ .van-submit-bar {
  .van-checkbox {
    padding-left: 15px;
  }
  & ~ .placeholder {
    height: 100px;
  }
}

/deep/ .van-goods-action {
  background: #fff;
  .van-checkbox {
    padding-left: 15px;
    padding-right: 15px;
    align-self: center;
  }
  & ~ .placeholder {
    height: 100px;
  }
}

.card-goods {
  &-box {
    background-color: #fff;
    -moz-box-align: center;
    -moz-box-pack: justify;
    align-items: center;
    align-content: space-around;
    box-sizing: border-box;
    display: -webkit-box;
    display: -webkit-flex;
    display: flex;
    justify-content: center;
    overflow: hidden;
    width: 100%;
    flex-wrap: nowrap;
    margin-bottom: 10px;
  }

  /deep/ .van-card:not(:first-child) {
    margin: 0;
  }

  /deep/ .van-card {
    -webkit-box-flex: 1;
    -webkit-flex: 1;
    flex: 1;
    padding: 10px 15px 10px 100px;
    height: 110px;
    background: #fff;
    &__thumb {
      top: 10px;
      left: 0;
    }
    &__footer {
      padding-right: 15px;
      padding-left: 100px;
      right: 0;
      bottom: 10px;
      width: 100%;
      .flexbox {
        > * {
          -webkit-box-flex: 1;
          -webkit-flex: 1;
          flex: 1;
        }
        .price-cny {
          font-size: 16px;
        }
        .price-cny:before {
          vertical-align: top;
        }
      }
      .van-button {
        margin: 0;
        width: 30px;
        height: 30px;
        border-radius: 0;
      }
    }
    .van-cell {
      margin: 5px 0;
      padding: 2px 10px;
      background: #f5f5f5;
      &__right-icon {
        transform: rotate(90deg);
        -ms-transform: rotate(90deg);
        -moz-transform: rotate(90deg);
        -webkit-transform: rotate(90deg);
        -o-transform: rotate(90deg);
      }
    }
    .van-stepper {
      text-align: right;
      &__minus,
      &__plus {
        width: 30px;
        height: 30px;
      }
    }
  }

  &__item {
    position: relative;
    text-align: center;

    /deep/ .van-checkbox__label {
      display: none;
    }

    /deep/ .van-checkbox__icon {
      padding: 44px 15px;
    }

    .van-card__price {
      color: #f44;
    }
  }
}
</style>
